<template>
  <div class="app-container">
    <HeadTool>
      <template #left>
        <span slot="left">共有 <strong>{{ pageInfo.total }}</strong> 条记录</span>
      </template>
      <template #right>
        <el-button size="small" type="success" icon="el-icon-document-checked" @click="exportExcel">导出</el-button>
        <el-button size="small" type="primary" icon="el-icon-document-add" @click="handleJump">导入</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="showDialog = true">新增员工</el-button>
      </template>
    </HeadTool>
    <el-card class="content">
      <el-table :data="tableData">
        <el-table-column align="center" type="index" label="序号" />
        <el-table-column align="center" prop="username" label="姓名" />
        <el-table-column align="center" prop="staffPhoto" label="头像">
          <template v-slot="{ row }">
            <img v-imgerr="defaultImg" class="staffPhoto" :src="row.staffPhoto ? row.staffPhoto : defaultImg" @click="clickPic(row.staffPhoto)">
          </template>
        </el-table-column>
        <el-table-column align="center" width="120" prop="mobile" label="手机号" />
        <el-table-column align="center" prop="workNumber" label="工号" sortable />
        <el-table-column align="center" width="100" prop="formOfEmployment" label="聘用形式" sortable>
          <template v-slot="{row}">
            <span>{{ row.formOfEmployment | formatHireType }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="departmentName" label="部门" sortable />
        <el-table-column align="center" width="100" prop="correctionTime" label="入职时间" sortable />
        <el-table-column align="center" prop="enableState" label="状态" sortable>
          <template v-slot="{row}">
            <el-switch v-model="row.enableState" active-color="#ff4949" inactive-color="#13ce66" disabled />
          </template>
        </el-table-column>
        <el-table-column align="center" width="260" fixed="right" label="操作">
          <template v-slot="{row}">
            <el-row type="flex" justify="space-between">
              <el-link v-if="checkPoint('POINT_EMP_EDIT')" :underline="false" type="primary" @click="check(row.id)">查看</el-link>
              <el-link :underline="false" type="primary">转正</el-link>
              <el-link :underline="false" type="primary">调岗</el-link>
              <el-link :underline="false" type="primary">离职</el-link>
              <el-link :underline="false" type="primary" @click="showRole(row.id)">角色</el-link>
              <el-link v-if="checkPoint('POINT_EMP_DEL')" :underline="false" type="primary" @click="doDel(row.id)">删除</el-link>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background :current-page.sync="pageInfo.page" :page-sizes="[5, 10, 30, 50]" :page-size="pageInfo.size" :total="pageInfo.total" layout="total, prev, pager, next, sizes, jumper" @current-change="loadData" @size-change="handleSizeChange" />
      <el-dialog class="dialog" width="20%" :visible="showQrCode" title="二维码" :show-close="false" @close="showQrCode = false">
        <canvas ref="canvas" />
      </el-dialog>
    </el-card>
    <AddEmp :show-dialog.sync="showDialog" />
    <!-- 分配角色的对话框 -->
    <el-dialog class="dialog" title="分配角色" :visible.sync="showRoleDialog" :show-close="false">
      <el-checkbox-group v-model="checkRoleList">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="showRoleDialog=false">取 消</el-button>
        <el-button size="small" type="primary" @click="assignRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getEmpList, deleteEmp, saveUserInfo } from '@/api/employees'
import { getRoleList } from '@/api/roles'
import { userProfile } from '@/api/user'
import AddEmp from './components/AddEmp.vue'
import { formatHireType } from '@/filters/filters'
import QRCode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmp
  },
  data() {
    return {
      tableData: [],
      pageInfo: {
        page: 1,
        size: 5,
        total: 0
      },
      defaultImg: require('@/assets/common/head.jpg'),
      checkRoleList: [],
      roleList: [],
      userInfo: {},
      showDialog: false,
      showQrCode: false,
      showRoleDialog: false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      const result = await getEmpList(this.pageInfo)
      this.tableData = result.data.rows
      this.pageInfo.total = result.data.total
    },
    handleSizeChange(newSize) {
      this.pageInfo.size = newSize
      this.loadData()
    },
    doDel(id) {
      this.$confirm('是否要删除此员工？', '提示', {
        center: true,
        closeOnClickModal: false,
        showClose: false,
        type: 'info'
      }).then(
        async() => {
          await deleteEmp(id)
          if (this.tableData.length === 1 && this.pageInfo.page !== 1) {
            this.pageInfo.page--
          }
          this.loadData()
        }
      ).catch(() => {})
    },
    handleJump() {
      this.$router.push(
        {
          path: '/import',
          query: {
            type: 'employees'
          }
        }
      )
    },
    exportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        const result = await getEmpList({
          page: 1,
          size: this.pageInfo.total
        })
        const list = result.data.rows
        const userRelations = {
          入职日期: 'timeOfEntry',
          手机号: 'mobile',
          姓名: 'username',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          聘用形式: 'formOfEmployment'
        }
        const header = Object.keys(userRelations)
        const data = list.map(value => {
          const temp = []
          for (const key in userRelations) {
            const enKey = userRelations[key]
            key === '聘用形式' ? temp.push(formatHireType(value[enKey])) : temp.push(value[enKey])
          }
          return temp
        })
        excel.export_json_to_excel({
          header,
          data,
          filename: '员工列表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    check(id) {
      this.$router.push(
        {
          name: 'detail',
          query: {
            id: id
          }
        }
      )
    },
    async clickPic(url) {
      this.showQrCode = true
      await this.$nextTick()
      QRCode.toCanvas(this.$refs.canvas, url)
    },
    async getRoleList() {
      const result = await getRoleList({
        page: 1,
        pageSize: 99999
      })
      this.roleList = result.data.rows
    },
    async getUserProfile(id) {
      const result = await userProfile(id)
      this.userInfo = result.data
      this.checkRoleList = result.data.roleIds
    },
    async showRole(id) {
      await this.getRoleList()
      await this.getUserProfile(id)
      this.showRoleDialog = true
    },
    async assignRole() {
      await saveUserInfo({
        ...this.userInfo,
        roleIds: this.checkRoleList
      })
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  margin-top: 20px;
  .staffPhoto {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
}
::v-deep .el-dialog, .dialog {
  border-radius: 10px;
  .el-dialog__header {
    background: linear-gradient(to right, #3e6ef8, #5b8cff);
    border-radius: 10px 10px 0 0;
  }
  .el-dialog__body {
    text-align: center;
  }
}
.el-pagination {
  text-align: center;
  margin-top: 14px;
}
</style>
